package com.jingdogn.utils;

import com.jingdogn.entity.Good;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class JDShop {

    private static final String SEARCHURL = "https://search.jd.com/Search?keyword=%s&enc=utf-8&psort=3&page=%d";

//    public static void main(String[] args) {
//        JDShop jdShop = new JDShop();
//        jdShop.getShopList(3, "电视机");
//    }

    public List<Good> getShopList(Integer maxPage, String key) {
        List<Good> goodList = new ArrayList<>();
        Integer index = 1;
        Integer size = 1;
        while ((index + 1) / 2 <= maxPage) {
            String url = String.format(SEARCHURL, key, index);
            //网址分析
            /*keyword:关键词（京东搜索框输入的信息）
             * enc：编码方式（可改动:默认UTF-8）
             * psort=3 //搜索方式  默认按综合查询 不给psort值
             * page=分业（不考虑动态加载时按照基数分业，每一页30条，这里就不演示动态加载）
             * 注意：受京东商品个性化影响，准确率无法保障
             * */
            Document doc = null;
            try {
                doc = Jsoup.connect(url).maxBodySize(0).get();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //doc获取整个页面的所有数据
            Elements ulList = null;
            if (doc != null) {
                ulList = doc.select("ul[class='gl-warp clearfix']");
            }
            Elements liList = null;
            if (ulList != null) {
                liList = ulList.select("li[class='gl-item']");
            }
            //循环liList的数据
            assert liList != null;
            for (Element item : liList) {
                //排除广告位置
                if (!item.select("span[class='p-promo-flag']").text().trim().equals("广告")) {
                    System.out.println(size);
//                    String  = ""
                    //如果向存到数据库和文件里请自行更改
//           /         System.out.println(item.select("div[class='p-name p-name-type-2']").select("a").attr("href"));//打印商品标题到控制台
                    String itmeUrl = "http:" + item.select("div[class='p-name p-name-type-2']").select("a").attr("href");
                    System.out.println(itmeUrl);
                    Good good = goodDetail(itmeUrl);
                    good.setUrl(itmeUrl);
                    goodList.add(good);
//                    System.out.println(item.select("div[class='p-name p-name-type-2']").select("em").text());//打印商品标题到控制台
                }
                size++;
            }
            index = index + 2;

        }
        return goodList;
    }


    public Good goodDetail(String url) {
//        https://p.3.cn/prices/mgets?skuIds=J_100009177424
        Good good = new Good();
        Document doc = null;
        try {
            doc = Jsoup.connect(url).maxBodySize(0).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Elements priceElement = doc.select("div[class='summary-price J-summary-price']");
        String price = priceElement.select("span[class='price J-p-3482385']").text();
        System.out.println("price:" + price);
//        Elements ulList = doc.select("ul[class='parameter2 p-parameter-list']");
//        String test = doc.select("/html/body/div[11]/div[2]/div[1]/div[2]/div[1]/div[1]/ul[2]").text();
//        System.out.println(test);
//        Elements testList = ulList.select("li");
//        for (Element item : testList) {
//            System.out.println(item.select("li").text());
//        }

        Elements elements = doc.select("div[class='Ptable-item']");
        Map<String, String> list = new LinkedHashMap<>();
        for (Element item : elements) {
//            System.out.println("-------start----------");
//            System.out.println(item.select("dl[class='clearfix']").text());
//            System.out.println("-------end----------");
            Elements elements1 = item.select("dl[class='clearfix']");
            elements1.forEach(element -> {
                list.put(element.select("dt").text(), element.select("dd").text());
//                System.out.println("标题：" + element.select("dt").text());
//                System.out.println("内容：" + element.select("dd").text());
            });
        }
        good.setGoodMap(list);
        return good;
    }
}
